<template>
  <div id="map" class="map" tabindex="0"></div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import Feature from "ol/Feature";
import { Point } from "ol/geom";
import { fromLonLat } from "ol/proj";
import { Fill, Circle, Style } from "ol/style";
import XYZ from 'ol/source/XYZ';
import { defaults as defaultControls } from 'ol/control';
import { getDataCenterListNew } from "@/api/map/newMap"
import { testData } from "./map";
export default {
  name: "openlayersMap",
  data() {
    return {
      map: null,
      resPdata: [],//点位数据
    };
  },

  mounted() {
    this.initMap();
    this.getMap();
  },
  methods: {
    // 初始化地图
    initMap() {
      this.map = new Map({
        layers: [
          new TileLayer({
            // 创建一个使用Open Street Map地图源的瓦片图层
            source: new XYZ({
              url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
              wrapX: false
            })
          }),
        ],
        target: "map",
        view: new View({
          zoom: 3, // 缩放
          // projection: 'EPSG:4326', // 坐标系
          // center: [100.990969, 36.635013], // 地图中心点
          center: [221.469170, 131.224361],
          minZoom: 1,
          maxZoom: 28,
          // multiWorld :false,
          // extent:[73.8, 3.9, 135.1, 53.5],//地图边界,打开后就不能拖动
          extent: fromLonLat([-180, -90]).concat(fromLonLat([180, 90])), // 设置地图边界
        }),
        //加载控件到地图容器中
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false
        }),
      });
    },

    // 获取后台数据
    getMap() {
      // 获取点位数据
      getDataCenterListNew().then((res) => {
        if (res.code === 200) {
          // console.log('res', res);
          this.resPdata = res.data;
          this.$store.state.rightDetails.firstMapData = res  
          // this.$store.state.rightDetails.firstMapData = testData

          this.drawTyphoonPath();
          this.designClickOnMap()
          this.designMoveOnMap()
          // console.log('this.resPdata', this.resPdata);
        }
      })
    },

    // 显示点
    drawTyphoonPath() {
      let data = []
      let assetCountData = ''
      let availableAreas = ''
      let cloudConponentSort = []
      let cloudServerCount = ''
      let cloudServerSort = []
      let country = ''
      let dataCenterName = ''
      let ipCount = ''
      let ipScale = []
      let ipSort = []
      let latitude = ''
      let location = ''
      let locationAbbreviate = ''
      let locationFullNameEn = ''
      let longitude = ''
      let portSort = []
      let protocolSort = []
      let severSort = []
      let type = ''
      let useAge = ''
      let webAppSort = []
      let webFrameSort = []
      let yearOpened = ''
      for (var i = 0; i < this.resPdata.length; i++) {
        // console.log('resPdata[i]', this.resPdata[i]);
        if (this.resPdata[i] && this.resPdata[i].longitude && this.resPdata[i].latitude) {
          // data.push({ longitude: this.resPdata[i].longitude, latitude: this.resPdata[i].latitude, dataCenterName: this.resPdata[i].dataCenterName })
          let obj = {}
          obj['assetCount'] = this.resPdata[i].assetCount
          obj['availableAreas'] = this.resPdata[i].availableAreas
          obj['cloudServerCount'] = this.resPdata[i].cloudServerCount
          obj['country'] = this.resPdata[i].country
          obj['dataCenterName'] = this.resPdata[i].dataCenterName
          obj['ipCount'] = this.resPdata[i].ipCount
          obj['latitude'] = this.resPdata[i].latitude
          obj['location'] = this.resPdata[i].location
          obj['locationAbbreviate'] = this.resPdata[i].locationAbbreviate
          obj['locationFullNameEn'] = this.resPdata[i].locationFullNameEn
          obj['longitude'] = this.resPdata[i].longitude
          obj['type'] = this.resPdata[i].type
          obj['useAge'] = this.resPdata[i].useAge
          obj['yearOpened'] = this.resPdata[i].yearOpened
          obj['cloudConponentSort'] = this.resPdata[i].cloudConponentSort&&JSON.parse(this.resPdata[i].cloudConponentSort)
          obj['cloudServerSort'] = this.resPdata[i].cloudServerSort&&JSON.parse(this.resPdata[i].cloudServerSort)
          obj['ipScale'] = this.resPdata[i].ipScale&&JSON.parse(this.resPdata[i].ipScale)
          obj['ipSort'] = this.resPdata[i].ipSort&&JSON.parse(this.resPdata[i].ipSort)
          obj['portSort'] = this.resPdata[i].portSort&&JSON.parse(this.resPdata[i].portSort)
          obj['protocolSort'] = this.resPdata[i].protocolSort&&JSON.parse(this.resPdata[i].protocolSort)
          obj['webAppSort'] = this.resPdata[i].webAppSort&&JSON.parse(this.resPdata[i].webAppSort)
          obj['webFrameSort'] = this.resPdata[i].webFrameSort&&JSON.parse(this.resPdata[i].webFrameSort)
          obj['severSort'] = this.resPdata[i].severSort&&JSON.parse(this.resPdata[i].severSort)
          data.push(obj)
        }
        
        // data.push(this.resPdata[i])
      }
      
      let points = data;
      let features = [];
      // console.log('points', points);

      for (let i = 0; i < data.length; i++) {
        let position = [points[i].longitude, points[i].latitude];
        let positionArr = fromLonLat(position)
        // console.log('positionArr', positionArr);

        if (!isNaN(positionArr[0]) && !isNaN(positionArr[1])) {
          let featurePoint = new Feature({
            geometry: new Point(positionArr),
          });

          featurePoint.setStyle(
            new Style({
              image: new Circle({
                fill: new Fill({
                  color: "#00B0FF",
                }),
                radius: 6,
              }),
            })
          );
          // console.log('@@points', points[i]);
          featurePoint.set('pointData', points[i])
          features.push(featurePoint);
        }
      }
      // 矢量图层
      let layer = new VectorLayer();
      // 矢量数据源
      let source = new VectorSource({
        wrapX: false
      });
      source.addFeatures(features);
      layer.setSource(source);
      this.map.addLayer(layer);
    },

    // 注册一个click事件
    designClickOnMap: function () {
      let _this = this;
      this.map.on("click", function (ev) {
        let pixel = ev.pixel;
        let width = pixel[0] / _this.$store.state.switch.scaleS;
        let height = pixel[1] / _this.$store.state.switch.scaleS;
        let pix = [width, height]
        // console.log(pix)
        let feature = _this.map.forEachFeatureAtPixel(
          pix,
          function (feature) {
            return feature;
          }
        );
        if (feature && feature.get('pointData')) {
          // console.log(`output->feature.get('typhoonPoint')`, feature.get('pointData'))
          _this.map.getTargetElement().style.cursor = "pointer";
          _this.getipData(feature.get('pointData'));
        } else {
          // console.log("no feature");
          _this.map.getTargetElement().style.cursor = "";
          _this.$store.state.switch.showDetail = false;
          _this.$store.state.switch.showDetailTwo = false;
        }
      });
    },
    // 注册一个click事件
    designMoveOnMap: function () {
      let _this = this;
      this.map.on("pointermove", function (ev) {
        let pixel = ev.pixel;
        let width = pixel[0] / _this.$store.state.switch.scaleS;
        let height = pixel[1] / _this.$store.state.switch.scaleS;
        let pix = [width, height]
        // console.log(pix)
        let feature = _this.map.forEachFeatureAtPixel(
          pix,
          function (feature) {
            return feature;
          }
        );
        if (feature && feature.get('pointData')) {
          // console.log(`output->feature.get('typhoonPoint')`, feature.get('pointData'))
          _this.map.getTargetElement().style.cursor = "pointer";
        } else {
          // console.log("no feature");
          _this.map.getTargetElement().style.cursor = "";
        }
      });
    },

    // 数据中心详情页赋值
    getipData(data) {
      this.$store.state.switch.showDetail = true; //控制详情页展开
      // console.log('data', data);
      this.$store.state.rightDetails.detailOneData = data
      // console.log('xqdata',data)
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
}

.cursor-pointer {
  cursor: pointer;
}
</style>
